package cn.xd.base.persistence.repository.impl;


import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.xd.base.basic.type.AdminMenuId;
import cn.xd.base.domain.entity.AdminMenu;
import cn.xd.base.domain.repository.AdminMenuRepository;
import cn.xd.base.persistence.dos.AdminMenuConverter;
import cn.xd.base.persistence.dos.AdminMenuDO;
import cn.xd.base.persistence.mps.AdminMenuMpService;
import cn.xd.core.ddd.db.DbRepositorySupport;
import cn.xd.core.ddd.diff.EntityDiff;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

@Repository
public class AdminMenuRepositoryImpl extends DbRepositorySupport<AdminMenu, AdminMenuId> implements AdminMenuRepository {
    @Resource
    private AdminMenuMpService adminMenuMpService;

    @Override
    protected void onInsert(AdminMenu aggregate) {
        adminMenuMpService.getAdminMenu(aggregate.getPerms().getValue(), null).isNotEmptyThrow("菜单标识已经存在");
        if (aggregate.getParentId().getValue() != 0) {
            adminMenuMpService.getResult(aggregate.getParentId()).isEmptyThrow("上级菜单不存在");
        }
        adminMenuMpService.saveResult(aggregate, AdminMenuConverter.INSTANCE).failThrow();
    }

    @Override
    protected AdminMenu onSelect(AdminMenuId id) {
        return adminMenuMpService.getResult(id, AdminMenuConverter.INSTANCE).get();
    }

    @Override
    protected void onUpdate(AdminMenu aggregate, EntityDiff diff) {
        if (diff.isSelfModified()) {
            AdminMenuDO bean = diff.getBean(AdminMenuDO.class);
            if (ObjUtil.isNotEmpty(bean.getParentId()) && bean.getParentId() != 0) {
                adminMenuMpService.getResult(aggregate.getParentId()).isEmptyThrow("上级菜单不存在");
            }
            if (StrUtil.isNotBlank(bean.getPerms())) {
                adminMenuMpService.getAdminMenu(aggregate.getPerms().getValue(), aggregate.getId().getValue()).isNotEmptyThrow("菜单标识已经存在");
            }
            adminMenuMpService.updateResult(bean);
        }
    }

    @Override
    protected void onDelete(AdminMenu aggregate) {
        adminMenuMpService.removeById(aggregate.getId().getValue());
    }

}
